/*
 * Copyright 2020 Google LLC. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xhkj.mylibrary.mlkit.facedetector

import android.content.Context
import android.util.Log
import com.aisway.flashy.utils.mlkit.VisionProcessorBase
import com.google.android.gms.tasks.Task
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.face.Face
import com.google.mlkit.vision.face.FaceDetection
import com.google.mlkit.vision.face.FaceDetector
import com.google.mlkit.vision.face.FaceDetectorOptions
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xhkj.mylibrary.mlkit.GraphicOverlay
import kotlin.math.sqrt

/** Face Detector Demo.  */
class FaceDetectorProcessor(context: Context, detectorOptions: FaceDetectorOptions?) :
    VisionProcessorBase<List<Face>>(context) {

    private val detector: FaceDetector

    init {
        val options = detectorOptions
            ?: FaceDetectorOptions.Builder()
                .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL)
                .enableTracking()
                .build()

        detector = FaceDetection.getClient(options)

        Log.v(MANUAL_TESTING_LOG, "Face detector options: $options")
    }

    override fun stop() {
        super.stop()
        detector.close()
    }

    override fun detectInImage(image: InputImage): Task<List<Face>> {
        return detector.process(image)
    }

    override fun onSuccess(results: List<Face>, graphicOverlay: GraphicOverlay) {
        if (results.isNotEmpty()) {
            for (face in results) {
                /*graphicOverlay.add(FaceGraphic(graphicOverlay, face))
                logExtrasForTesting(face)*/
                val allContours = face.allContours
                val eyes = allContours.filter {
                    it.points.size == 16
                }
                if (eyes.isNotEmpty()) {
                    val leftPoint = eyes[0].points
                    val rightPoint = eyes[1].points

                    val leftEyePoint = leftPoint[0]
                    val rightEyePoint = rightPoint[0]

                    val value =
                        (leftEyePoint.x - rightEyePoint.x) * (leftEyePoint.x - rightEyePoint.x) + (leftEyePoint.y - rightEyePoint.y) * (leftEyePoint.y - rightEyePoint.y)

                    if (value > 0) {
                        val radius = sqrt(value.toDouble())
                        if (radius > 0) {   //返回根据图片流测得的人物与摄像头的距离
                            LiveEventBus.get<Int>("FACE_NUM").post(radius.toInt())
                        }
                    }
                }
            }
        } else {    //没有检测到人脸
            LiveEventBus.get<Int>("FACE_IS_EMPTY").post(results.size)
        }
    }

    override fun onFailure(e: Exception) {
        Log.e(TAG, "Face detection failed $e")
    }

    companion object {
        private const val TAG = "FaceDetectorProcessor"
    }
}
